package gw.com.android.ui.quotesearch;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;

import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.quotesearch.adapter.HotProductAdapter;
import gw.com.android.ui.quotesearch.adapter.SearchAdapter;
import gw.com.android.ui.views.ClearableEditText;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.JsonUtil;
import www.com.library.view.RecyclerClickListener;
import www.com.library.view.RecyclerViewDecoration;

/**
 *
 * Created by reeta.zou on 2017/2/23.
 */

public class QuoteSearchActivity extends BaseActivity {

    @BindView(R.id.et_search)
    ClearableEditText mEtSearch;
    /* 搜索UI*/
    @BindView(R.id.view_search_main)
    View mViewSearch;
    @BindView(R.id.rcv_search)
    RecyclerView mRcvSearch;
    SearchAdapter mSearchAdapter;
    LinearLayoutManager mSearchLayoutManager;
    @BindView(R.id.view_empty)
    View mViewEmptySearch;

    /*历史搜索和热门搜索UI*/
    @BindView(R.id.view_search_hot_and_his)
    View mViewHotAndHis;
    @BindView(R.id.view_hot_product)
    View mViewHotProduct;
    @BindView(R.id.view_his_search)
    View mViewHisSearch;
    @BindView(R.id.rcv_his_search)
    RecyclerView mRcvHisSearch;
    @BindView(R.id.rcv_hot_product)
    RecyclerView mRcvHotProduct;
    SearchAdapter mHisSearchAdapter;
    HotProductAdapter mHotProductAdapter;
    LinearLayoutManager mHisSearchLayoutManager;
    GridLayoutManager mHotProductLayoutManager;

    private DataItemResult mHotProducts = new DataItemResult();
    private DataItemResult mHisSearch = new DataItemResult();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onSendQuote();
        PackStatis.getToService(PackStatis.EventAction.LOADING.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,null);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_quote_search;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(AppMain.getAppString(R.string.quote_title_search));
        //mTitleBar.setLeftResource(R.string.main_menu_item_quote);

        // 搜索
        mSearchLayoutManager = new LinearLayoutManager(this);
        mRcvSearch.setLayoutManager(mSearchLayoutManager);
        mSearchAdapter = new SearchAdapter(this, new DataItemResult());
        mRcvSearch.setAdapter(mSearchAdapter);

        // 历史搜索
        mHisSearchAdapter = new SearchAdapter(this, new DataItemResult());
        mHisSearchLayoutManager = new LinearLayoutManager(this);
        mRcvHisSearch.setLayoutManager(mHisSearchLayoutManager);
        mRcvHisSearch.setNestedScrollingEnabled(false);
        mRcvHisSearch.setAdapter(mHisSearchAdapter);

        // 热门产品
        mHotProductAdapter = new HotProductAdapter(this, new DataItemResult());
        mRcvHotProduct.addItemDecoration(new RecyclerViewDecoration((int)getResources().getDimension(R.dimen.space_d)));
        mHotProductLayoutManager = new GridLayoutManager(this, 3);
        mHotProductLayoutManager.setAutoMeasureEnabled(true);
        mRcvHotProduct.setLayoutManager(mHotProductLayoutManager);
        mRcvHotProduct.setAdapter(mHotProductAdapter);

        // 监听器
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = s.toString();
                handleKeySearch(key);
            }
        });
        mEtSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    // 此处为得到焦点时的处理内容
                    PackStatis.getToService(PackStatis.EventAction.CLICKINPUT.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,null);
                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });
    }

    @Override
    protected void initViewData() {
        // 初始化
        handleKeySearch("");
        getHotProduct();// 获取热门产品
        getHistoryProduct();//获取历史搜索数据

        //搜索结果点击之后添加历史搜索记录
        mSearchAdapter.setRecyclerClickListener(new RecyclerClickListener() {
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
                AppTerminal.instance().addProductToHistory(itemDetail.getInt(GTSConst.JSON_KEY_CODEID));
            }
        });
        mHotProductAdapter.setRecyclerClickListener(new RecyclerClickListener() {
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
//                AppTerminal.instance().addProductToHistory(itemDetail.getInt(GTSConst.JSON_KEY_CODEID));
            }
        });
    }

    @Override
    protected void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    @Override
    protected void onResume() {
        super.onResume();
        String key = mEtSearch.getText().toString();
        handleKeySearch(key);
    }

    @OnClick(R.id.tv_clear)
    void clearHisSearch() {
        if(CommonUtils.isFastDoubleClick()){
            return;
        }
        mHisSearch = new DataItemResult();
        AppTerminal.instance().removeAllProductHistory();
        updateHotAndHis();
        PackStatis.getToService(PackStatis.EventAction.CLICKDELETEALL.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,null);
    }

    // 如果key不为空，则执行搜索， 否则显示历史和热门
    private void handleKeySearch(String key) {
        if(TextUtils.isEmpty(key)) {
            mEtSearch.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font_e));
            mViewHotAndHis.setVisibility(View.VISIBLE);
            mSearchAdapter.updateData(new DataItemResult());
            mViewSearch.setVisibility(View.GONE);
            getHistoryProduct();
        }else {
            mEtSearch.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font_c));
            mViewHotAndHis.setVisibility(View.GONE);
            mViewSearch.setVisibility(View.VISIBLE);
            search(key);
            PackStatis.getToService(PackStatis.EventAction.CLICKSEARCH.getValue(), PackStatis.EventCategory.SEARCH.getValue(),null,key);
        }
    }

    /**
     * 搜索关联
     * @param key
     */
    private void search(String key) {
        DataItemResult result = new DataItemResult();
        String resultStr = AppTerminal.instance().searchProductList(key);
        try {
            if(JsonUtil.isJsonData(resultStr)){
                JSONArray mArray = new JSONArray(resultStr);
                JsonUtil.toDataItemResult(result, mArray);
            }
            //设置自选标识
            for (int  i = 0 ; i < result.getDataCount(); i++){
                DataItemDetail itemDetail = result.getItem(i);
                if(null != itemDetail){
                    if(DataManager.instance().isSelfPro(itemDetail.getInt(GTSConst.JSON_KEY_CODEID))){
                        itemDetail.setIntValue(GTSConst.JSON_KEY_ISSELECTED,1);
                    }
                }
            }
            handleSearchResult(key, result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*处理搜索结果*/
    private void handleSearchResult(String key, DataItemResult data) {
        if(data.getDataCount() <= 0) {
            mViewEmptySearch.setVisibility(View.VISIBLE);
            mRcvSearch.setVisibility(View.GONE);
        }else {
            mViewEmptySearch.setVisibility(View.GONE);
            mRcvSearch.setVisibility(View.VISIBLE);
            mSearchAdapter.updateData(data);
        }
    }

    /**
     * 获取热门产品数据
     */
    private void getHotProduct() {
        String result = AppTerminal.instance().getHotProductList(9);
        try {
            if(JsonUtil.isJsonData(result)){
                JSONArray mArray = new JSONArray(result);
                mHotProducts.clear();
                JsonUtil.toDataItemResult(mHotProducts, mArray);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取历史搜索数据
     */
    private void getHistoryProduct(){
        String hisResult = AppTerminal.instance().getAllProductHistory();
        try {
            if(JsonUtil.isJsonData(hisResult)){
                JSONArray mArray2 = new JSONArray(hisResult);
                mHisSearch.clear();
                JsonUtil.toDataItemResult(mHisSearch, mArray2);

                //设置自选标识
                for (int  i = 0 ; i < mHisSearch.getDataCount(); i++){
                    DataItemDetail itemDetail = mHisSearch.getItem(i);
                    if(null != itemDetail){
                        if(DataManager.instance().isSelfPro(itemDetail.getInt(GTSConst.JSON_KEY_CODEID))){
                            itemDetail.setIntValue(GTSConst.JSON_KEY_ISSELECTED,1);
                        }
                    }
                }
            }
            updateHotAndHis();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 更新历史和热门， 如果数据为空，则隐藏
    private void updateHotAndHis() {
        if(mHotProducts == null || mHotProducts.getDataCount() <= 0) {
            mViewHotProduct.setVisibility(View.GONE);
        }else {
            mViewHotProduct.setVisibility(View.VISIBLE);
            mHotProductAdapter.updateData(mHotProducts);
        }

        if(mHisSearch == null || mHisSearch.getDataCount() <= 0) {
            mViewHisSearch.setVisibility(View.GONE);
        }else {
            mViewHisSearch.setVisibility(View.VISIBLE);
            mHisSearchAdapter.updateData(mHisSearch);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //图表界面点击返回到主面板
        Logger.e("QuoteSearchActivity 图表界面返回到主面板 ");
        GTTKDataManager.instance().clearTimeData();
        GTTKDataManager.instance().clearKData();
        GTTKDataManager.instance().clearIndictor();
        AppTerminal.instance().clearAllChartCache();
        if(resultCode == AppContances.RESULT_CODE){
            Logger.e("QuoteSearchActivity 交易界面直接返回到主面板 ");
            setResult(AppContances.RESULT_CODE);
            finish();
        }
    }
}
